package com.haonan.Filter;

import com.haonan.Utils.CurrentHolder;
import com.haonan.Utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter("/*")
public class TokenFiler implements Filter {
    //初始化
    public void init(FilterConfig filterConfig) throws ServletException {//初始化
        Filter.super.init(filterConfig);
    }

    //拦截请求
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        //强转 将请求转为Http请求
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求路径
        String path = request.getServletPath();
        if (path.contains("/login")){
            chain.doFilter(request,response);
        }
        //3.获取token
        String token = request.getHeader("token");
        //4.判断token是否为空，如果是，则返回状态码401
        if (token==null || token.isEmpty()){
            response.setStatus(401);
            return;
        }
        //5.判断token是否正确，不正确则返回状态码401
        Claims claims = JwtUtils.parseJWT(token);
        CurrentHolder.setCurrentId((Integer) claims.get("id"));
        if (claims==null){
            response.setStatus(401);
            return;
        }
        //6.放行
        chain.doFilter(request,response);
        CurrentHolder.remove();

    }

    //销毁
    public void destroy() {
        Filter.super.destroy();
    }
}
